﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Turtle
{
    /// <summary>
    /// Turtle as a Value Object.
    /// </summary>
    public class TurtleImmutable
    {

        private readonly Position _pos;
        private readonly double _dir;
        
        public Position Position { get { return _pos; }}
        public double Direction  { get { return _dir; }}

        private const int _delta = 1;

        public TurtleImmutable()
        {
            _pos = new Position(0,0);
            _dir = 0.0;
        }

        public TurtleImmutable(Position position, double direction)
        {
            _pos = position;
            _dir = direction;
        }

        public TurtleImmutable Go()
        {
            var newX = (int) Math.Round(Position.X + _delta * Math.Cos(Direction));
            var newY = (int) Math.Round(Position.Y + _delta * Math.Sin(Direction));

            var newPosition = new Position(newX, newY);
            
            return new TurtleImmutable(newPosition, Direction);
        }

        public TurtleImmutable Rotate(double delta)
        {
            var newDirection = Direction + delta;
            return new TurtleImmutable(Position, newDirection);
        }

    }

    public static class TurtleImmutableExtensions
    {
        public static TurtleImmutable Left(this TurtleImmutable turtle)
        {
            var newTurtle = turtle.Rotate(Math.PI / 2);
            return new TurtleImmutable(newTurtle.Position, newTurtle.Direction);
        }

        public static TurtleImmutable Right(this TurtleImmutable turtle)
        {
            var newTurtle = turtle.Rotate(-Math.PI / 2);
            return new TurtleImmutable(newTurtle.Position, newTurtle.Direction);
        }

        public static TurtleImmutable GoSteps(this TurtleImmutable turtle, int steps)
        {

            if (steps == 0)
                return turtle;

            for (int i = 1; i <= steps; i++)
            {
                turtle = turtle.Go();
            }
            
            return new TurtleImmutable(turtle.Position, turtle.Direction);
        }

    }
}
